package mybaidu

import (
	"data/config"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"public/mycache"
	"public/mylog"
	"time"
)

const (
	GETTOKENURL      = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="
	FACEDETECTURL    = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token="
	FACEADDURL       = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token="
	FACESEARCHURL    = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token="
	FACEGETLISTURL   = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist?access_token="
	GROUPGETUSERSURL = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getusers?access_token="
	GROUPGETLISTURL  = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getlist?access_token="
	FACEMATCHURL     = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token="
	IDCARDURL        = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token="
)

/*
	获取百度sdk accesstoken
*/
func OnGetAccessToken() string {
	//获取
	cache := mycache.OnGetCache("baidu_")
	var tp interface{}
	tp, ret := cache.Value("accesstoken")
	if ret {
		return tp.(string)
	}

	accesstoken := getBaiduAccessToken()
	if len(accesstoken) > 0 {
		cache.Add("accesstoken", accesstoken, 25*24*time.Hour) //25天过期
	}
	return accesstoken

}

func getBaiduAccessToken() string {
	k, v := config.GetBaiduInfo()
	url := GETTOKENURL + k + "&client_secret=" + v
	httpClient := http.Client{}
	httpReq, _ := http.NewRequest("GET", url, nil)
	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		mylog.Error(err)
		return ""
	}
	defer httpResp.Body.Close()
	body, _ := ioutil.ReadAll(httpResp.Body)

	stb := BaiduToken{}
	json.Unmarshal(body, &stb)
	return stb.Access_token
}
